package com.heatingcharge.service.unit.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.BeanValidator;
import com.heatingcharge.common.util.ResponseCodeEnum;
import com.heatingcharge.dto.ResHouseDTO;
import com.heatingcharge.entity.unit.HouseChangeRecord;
import com.heatingcharge.entity.unit.ResHouse;
import com.heatingcharge.entity.unit.ResZone;
import com.heatingcharge.mapper.unit.HouseChangeRecordMapper;
import com.heatingcharge.mapper.unit.ResHouseMapper;
import com.heatingcharge.param.ResHouseParam;
import com.heatingcharge.param.SearchParam;
import com.heatingcharge.security.JwtUser;
import com.heatingcharge.security.util.SecurityUtil;
import com.heatingcharge.service.unit.IResHouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heatingcharge.vo.TreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 房屋信息 服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-07-12
 */
@Service
public class ResHouseServiceImpl extends ServiceImpl<ResHouseMapper, ResHouse> implements IResHouseService {

    @Autowired
    HouseChangeRecordMapper houseChangeRecordMapper;

    @Override
    public IPage<ResHouseDTO> getHouses(Page page, ResHouseDTO resHouseDTO) {
        return baseMapper.selectHouses(page,resHouseDTO);
    }

    @Override
    public List<ResHouseDTO> getHouses(SearchParam searchParam) {
        return baseMapper.selectHouses(searchParam);
    }


    @Override
    public List<TreeVo> getHouses(ResHouseDTO resHouseDTO) {
        return null;
    }

    @Override
    public boolean save(ResHouseParam resHouseParam) {
        //校验字段合法性
        BeanValidator.check(resHouseParam);
        //检验房间是否已经存在
        if (checkExist(resHouseParam.getUnitId(),resHouseParam.getNum(),null)){
            //房间已经存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_EXIST.getCode());
        }
        ResHouse resHouse=ResHouse.builder()
                .num(resHouseParam.getNum())
                .unitId(resHouseParam.getUnitId())
                .buildArea(resHouseParam.getBuildArea())
                .useArea(resHouseParam.getUseArea())
                .heatArea(resHouseParam.getHeatArea())
                .chargeArea(resHouseParam.getChargeArea())
                .floorHeight(resHouseParam.getFloorHeight())
                .floorFactor(resHouseParam.getFloorFactor())
                .houseType(resHouseParam.getHouseType())
                .chargeType(resHouseParam.getChargeType())
                .heatStatus(resHouseParam.getHeatStatus())
                .isActivate(resHouseParam.getActivate())
                .activateTime(resHouseParam.getActivateTime())
                .cardNum(resHouseParam.getCardNum())
                .build();
        return baseMapper.insert(resHouse)>0;
    }
    /**
     * 当前单元中是否存在此房屋
     * @param unitId
     * @param num
     * @param id
     * @return
     */
    private boolean checkExist(Integer unitId,String num,Integer id) {
        QueryWrapper<ResHouse> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("unit_id",unitId);
        queryWrapper.eq("num",num);
        if (id!=null){
            queryWrapper.ne("id",id);
        }
        return this.list(queryWrapper).size()>0;
    }
    @Override
    public boolean update(ResHouseParam resHouseParam) {
        //校验字段合法性
        BeanValidator.check(resHouseParam);
        //检验房间是否已经存在
        if (checkExist(resHouseParam.getUnitId(),resHouseParam.getNum(),resHouseParam.getId())){
            //房间已经存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_EXIST.getCode());
        }
        ResHouse before=baseMapper.selectById(resHouseParam.getId());
        if (ObjectUtil.isNull(before)){
            //待更新的房间不存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_NON_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_NON_EXIST.getCode());
        }
        ResHouse after=new ResHouse();
        BeanUtils.copyProperties(resHouseParam,after);
        Integer ressult = baseMapper.updateById(after);
        //添加房间变更记录
        if(propertiesChanged(resHouseParam,before)){
            JwtUser user = SecurityUtil.getUser();
            HouseChangeRecord houseChangeRecord=HouseChangeRecord.builder()
                    .houseId(before.getId())
                    .buildArea(before.getBuildArea())
                    .useArea(before.getUseArea())
                    .heatArea(before.getHeatArea())
                    .chargeArea(before.getChargeArea())
                    .floorHeight(before.getFloorHeight())
                    .floorFactor(before.getFloorFactor())
                    .houseType(before.getHouseType())
                    .chargeType(before.getChargeType())
                    .heatStatus(before.getHeatStatus())
                    .changedReason(resHouseParam.getChangeReason())
                    .operator(user.getRealName())
                    .build();
            ressult = houseChangeRecordMapper.insert(houseChangeRecord);
        }
        return ressult>0;
    }

    @Override
    public boolean net(ResHouseParam resHouseParam) {
        ResHouse before=baseMapper.selectById(resHouseParam.getId());
        if (ObjectUtil.isNull(before)){
            //待更新的房间不存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_NON_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_NON_EXIST.getCode());
        }
        ResHouse after= ResHouse.builder()
                .id(resHouseParam.getId())
                .activateTime(resHouseParam.getActivateTime())
                .build();
        Integer ressult = baseMapper.updateById(after);
        return ressult>0;
    }

    @Override
    public boolean unet(ResHouseParam resHouseParam) {
        ResHouse before=baseMapper.selectById(resHouseParam.getId());
        if (ObjectUtil.isNull(before)){
            //待更新的房间不存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_NON_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_NON_EXIST.getCode());
        }
        ResHouse after= ResHouse.builder()
                .id(resHouseParam.getId())
                .activateTime(null)
                .build();
        UpdateWrapper<ResHouse> wrapper=new UpdateWrapper<>();
        wrapper.set("activate_time",null);
        wrapper.eq("id",resHouseParam.getId());
//        wrapper
        return baseMapper.update(null,wrapper)>0;
    }

    @Override
    public boolean register(ResHouseParam resHouseParam) {
        ResHouse before=baseMapper.selectById(resHouseParam.getId());
        if (ObjectUtil.isNull(before)){
            //待更新的房间不存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_NON_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_NON_EXIST.getCode());
        }
        ResHouse after= ResHouse.builder()
                .id(resHouseParam.getId())
                .cardNum(resHouseParam.getCardNum())
                .build();
        Integer ressult = baseMapper.updateById(after);
        return ressult>0;
    }

    @Override
    public boolean destory(ResHouseParam resHouseParam) {
        ResHouse before=baseMapper.selectById(resHouseParam.getId());
        if (ObjectUtil.isNull(before)){
            //待更新的房间不存在
            throw new BaseException(ResponseCodeEnum.RESHOUSE_NON_EXIST.getMessage(),ResponseCodeEnum.RESHOUSE_NON_EXIST.getCode());
        }
        ResHouse after= ResHouse.builder()
                .id(resHouseParam.getId())
                .activateTime(null)
                .build();
        UpdateWrapper<ResHouse> wrapper=new UpdateWrapper<>();
        wrapper.set("card_num",null);
        wrapper.eq("id",resHouseParam.getId());
        return baseMapper.update(null,wrapper)>0;
    }

    private boolean propertiesChanged(ResHouseParam resHouseParam, ResHouse resHouse) {
        if (!Objects.equals(resHouseParam.getBuildArea(), resHouse.getBuildArea())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getUseArea(), resHouse.getUseArea())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getHeatArea(), resHouse.getHeatArea())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getChargeArea(), resHouse.getChargeArea())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getFloorHeight(), resHouse.getFloorHeight())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getFloorFactor(), resHouse.getFloorFactor())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getHeatStatus(), resHouse.getHeatStatus())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getHouseType(), resHouse.getHouseType())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getActivateTime(), resHouse.getActivateTime())){
            return true;
        }
        if (!Objects.equals(resHouseParam.getHeatStatus(), resHouse.getHeatStatus())){
            return true;
        }
        return false;
    }
}
